import requests
import os
import json
from datetime import datetime

SOOTANG_SAVE_DIR = "download/sootang"
SOOTANG_URL = "https://pf.sootang.com/service-api/products/page?sids=&keyword=&launchOrder=desc&cutOffOrder="
SOOTANG_LOOP_TIMES = 50;


def get_result(data):
    timestamp = data['cutOffTimeEnd']
    barcode = data['barcode']
    dt_object = datetime.strptime(data['date'], '%Y-%m-%d')
    timestamp = dt_object.timestamp()  # 转换为时间戳
    dt_object = datetime.fromtimestamp(timestamp)
    formatted_time = dt_object.strftime('%a+%b+%d+%Y+%H:%M:%S+GMT')  # 转换为字符串
    url = SOOTANG_URL+ '&cutOffTimeEnd=' + formatted_time + "&page="

    now = datetime.now()
    year = now.year
    month = now.month
    day = now.day
    today = str(year) + '-' + str(month) + '-' + str(day)
    result = get_sootang_data(SOOTANG_LOOP_TIMES,url,today,barcode)
    return result

def get_sootang_data(times, url, today, barCode):
    
    img_path_return = {'img_path':'','filename':'','date':''}
    result = []
    barCode = barCode.split("\n")
    print(barCode)
    for bar in barCode:
        stop_flag = False
        for i in range(times):
            page = str(i+1)
            new_url = url + page
            print(new_url)
            response = requests.get(new_url)
            if response.status_code == 200:
                data = response.text
                data = json.loads(data)
                content = data['content']
                for item in content:
                    if item['barCode'] == bar:
                        img_path_return = download_sootang_image(item['sliderImage'],today,bar)
                        # print(new_url)
                        stop_flag = True
                        break
                else:
                    continue
            if stop_flag :
                break
        result.append(img_path_return)
    return {'date': today,'result': result}

def download_sootang_image(url, today, barCode):
    # print(urlArr)
    save_dir = os.path.join(SOOTANG_SAVE_DIR, today)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    img_path = ''
    filenameArr = ''
    splitted = url.split('.')
    ext = splitted[len(splitted)-1]
    filename = barCode + '.'+ ext
    # print(splitted[len(splitted)-1])
    response = requests.get(url)
    if response.status_code == 200:
        with open(os.path.join(save_dir, filename), "wb") as f:
            img_path = os.path.join(save_dir, filename)
            filenameArr = filename
            f.write(response.content)
        print("图片下载成功:", filename)
    else:
        print("图片下载失败")

    return {'img_path':img_path,'fileName':filenameArr,'date':today,'barCode':barCode}

from application.util.mysql import MySQLHelper    
db = MySQLHelper(host="192.168.168.129", user="nanfeng", password="nanfeng", database="test5")
res = db.execute('SELECT * FROM user')
res = db.fetchall('SELECT * FROM user')
print(db,res)